declare var $:any;
declare var jQuery:any;
//首页
import { Component,OnInit } from '@angular/core';
import { UserComponent } from '../../components/user/user.component';
import { LoginService } from '../../services/login.service';
import { ConfigService } from '../../services/config.service';
import { getStampService } from '../../services/getStamp.service';
import { UIRouter } from '@uirouter/angular';
import axios from 'axios';
import { homeState,activityState,reportState} from "../../state/state.model" 
import { isWeixin,isFeixin } from "../../services/browser.service" 


@Component({
  selector: 'home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent {
    /*localStorage 情况：
    'msgId' 统一验证的信息
    */
    stampId = 0;//邮戳 1-10 + 11
    phoneNum = '';//用户号码
    userName = '';
    userNum = ''
    msgId ='';//取号用id
    message ='';//debug
    message2 ='';//debug
    phone_error = true;//手机号输入判断
    sms_error = false;//验证码输入判断
    phone_input = '';//手机号输入存储
    sms_input = '';//短信验证输入存储
    allowSubmit = false; //是否允许提交手机号+验证码
    allowSms = true;
    smsCount = 0;
    constructor(
                private router: UIRouter,
                private loginService: LoginService,
                private configService: ConfigService,
                private GetStampService:getStampService
                ){}
    currentUrl = '';  
    btnHide = true;  
    loginHide = true;      
    ngOnInit(){

        // setInterval(function(){
        //     console.log(new Date().getTime());
        // },1000);
        $("body").css("overflow","hidden");  
        // this.checkBrowser();
        this.judgeUrl();
        this.checkAll();
        // alert(localStorage.getItem('msgId'));
        // alert(localStorage.getItem('phone'));
        this.initMsgId();
        this.currentUrl = encodeURI(this.configService.getPrevUrl1()
                        +'cmpassport/znGetPhoneCallback.do?yxbMid='+this.msgId);
        // this.login302();
        // this.login();
        this.myAnimate();
    }   
    getSmsCount(){
        return (!!this.smsCount)?this.smsCount:'';
    }
    checkBrowser(){
        //alert(navigator.userAgent.toLowerCase());
        if(isWeixin(navigator.userAgent.toLowerCase())
            ||isFeixin(navigator.userAgent.toLowerCase())){
                
            }
            else{
                //this.unsupport();
            }
    }
    //登录部分的入口：
    
    unsupport(){
        window.location.href = this.configService.getYxbUrl()+"unsupport";
    }
   
    /*res.data:
    resultCode: xxx
    data: {
        phone.....
    }
    */
    //判断微信环境？wifi环境？
    //生成一个随机特征码
    getMsgId() {
        function S4() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }
        return (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4()) + '_' + new Date().getTime();
    }
    initMsgId(){
        var self = this;
        var msg = localStorage.getItem('msgId');
        if(msg==null){
            this.msgId = this.getMsgId();
            this.login302();
            // alert('1')
        }
        else if(localStorage.getItem("phone") == null){
            this.msgId = this.getMsgId();            
            this.login302();
            // alert('2')
        }
        else{
            this.msgId = msg;
            this.autoLogin();
            // alert('3')
        }
        this.saveMsgLocal(this.msgId);
    }
    autoLogin(){
        this.phoneNum = localStorage.getItem("phone");
        var self = this;
        self.loginService.getUser(self.phoneNum).then(
            (res)=>{
                    if(res.data.msg.name){
                        self.userName = res.data.msg.name;
                    }
                    else{
                        self.userName = "小镇居民"
                    }
                    localStorage.setItem('name',self.userName);
                    self.btnAnimate();
            }
        ).catch((error)=>{
            alert('网络无连接，请刷新后重试（1）。')
        //     self.userName = "小镇居民"
        // localStorage.setItem('name',self.userName);
        // self.btnAnimate();
        })
    }
    //生成时间戳    
    timestamp(){
        var  time  =  new Date();
        var  y  =  time.getFullYear();
        var  m  =  time.getMonth() + 1;
        var  d  =  time.getDate();
        var  h  =  time.getHours();
        var  mm  =  time.getMinutes();
        var  s  =  time.getSeconds();
        var  sw  =  time.getMilliseconds();
        function  add0(m) {
            return  m < 10 ? '0' + m  :  m;
        }
        return  ''+y + add0(m) + add0(d) + add0(h) + add0(mm) + add0(s) + add0(sw);
    }

    //将msgId存到本地缓存里
    saveMsgLocal(msg){
        localStorage.setItem('msgId',msg);
    }

    cookieEnd() {
        var date = new Date();
        date.setTime(date.getTime() + (15 * 60 * 1000)); //15分后的这个时候过期
        return date;
    }
    //====================================================
    myAnimate(){
        
        $('.title').enter("bounceInDown");
        // $('.title').enter("zoomIn");
        $('.logo').enter("zoomIn");
        $('.firework').enter();
                     
    }
    btnAnimate(){
        this.btnHide = false;       
        $('.get-btn').enter('zoomIn'); 
        $('.user').enter("bounceInDown");
    }
    //------------
    login302(){
        var self = this;
        $.ajax({
            type: 'POST',
            url: this.configService.getAccessTokenUrl(),
            data: {},
            dataType: 'json',
            contentType:"text/plain",
            success: function (data) {
                // alert('getAccessTokenUrl-s');
                // alert(stringifyJSON(data));
                if(data.resultCode === 0){
                    //请求accessToken信息成功，区分环境
                    self.environmentDiff(data);
                }else{
                    //不能正常请求accessToken，短信验证方式登录,弹短信登录认证框
                    self.show_login_type1()
                }
            },
            error:function (data) {
                // alert('getAccessTokenUrl-e');
                // alert(stringifyJSON(data));
                // alert("test "+"login302 err")
                //不能正常请求accessToken，短信验证方式登录,弹短信登录认证框
                self.show_login_type1()
            }
        });
    }

    environmentDiff(data){
        this.dispose(data,'sign');
    }
    dispose(data,sign){
        var self = this;
        var signStr = sign?"&sign="+ sign:"";
        // alert("条件函数执行")
        if(!data.data.timestamp){
            data.data.timestamp = this.timestamp();
        }
        var img = document.createElement("img");
        img.src = this.configService.getPrevUrl2()
                +"getMobileR?ver=1.0&appId="+ this.configService.getAppId() 
                +"&msgId="+this.msgId
                +"&timestamp="+data.data.timestamp
                +"&accessToken="+data.data.accessToken
                +"&openType=1&message="+this.msgId
                +"&expandParams="+ this.configService.getPhoneNumStr()+signStr 
                +"&redirectUrl="+this.currentUrl;
        img.id = "login_img";
        img.style.display = "none";
        document.body.appendChild(img);
        //之后再向后台请求获取这个号码
        $(img).on('load',function(){
            // 加载完成，token校检成功
            // alert("test "+'成功');
            self.getMsgId_queryPhoneNum2();
        })
        $(img).on('error',function(data){
            //token校检失败，短信验证方式登录,弹短信登录认证框
            // alert("test :"+'图片加载失败');
            console.log(data);

            self.show_login_type1();
        });
    }

    getMsgId_queryPhoneNum2() {
        //请求手机号码
        var self = this;
        $.ajax({
            type: 'POST',
            url: this.configService.getPhoneUrl(),
            data: JSON.stringify({"msgId":this.msgId}),
            contentType:"text/plain",
            dataType: 'json',
            success: function(data){
                // alert('getPhoneUrl-s');
                // alert(stringifyJSON(data));
                if(data.resultCode === 0){
                    // alert('success!');
                    //能正常请求手机号码，自动取号方式登录,弹自动取号登录认证框
                    // alert(data.data.phone);
                    self.show_login_type0(data);

                }else{
                    //不能正常请求手机号码，短信验证方式登录,弹短信登录认证框
                    
                    self.show_login_type1();

                }
            },
            error: function(){
                // alert('test : queryNum err')
                self.show_login_type1();
            }
        });
    }
    show_login_type0(data){
        var self = this;
        localStorage.setItem("phone",data.data.phone);
        // alert('phone : ' + data.data.phone);
        self.phoneNum = data.data.phone;
        self.loginService.getUser(self.phoneNum).then(
            (res)=>{
                if(res.data.msg.name){
                    self.userName = res.data.msg.name;
                }
                else{
                    self.userName = "小镇居民"
                }
                localStorage.setItem("name",self.userName);
                self.btnAnimate();
            }
        ).catch((error)=>{
            alert('网络无连接，请刷新后重试（2）。')
            //window.location.reload();
        })
    }
    show_login_type1(){
        // alert("手动填写表单。")
        
        this.loginWindow();
    }
    loginWindow(){
        this.loginHide = !this.loginHide;
    }
    toActivity(){

        var self = this;
        localStorage.setItem("phone",self.phoneNum);
        self.GetStampService.getStamp(self.phoneNum,self.stampId).then((res) => {
            if(res.data.code == 0){
                alert("你已领取过该邮戳喔~");
            }else if(res.data.code == 2){
                alert("领取失败");
            } 
            // self.router.navigate(["/activity"]);
            window.location.href = self.configService.getYxbUrl() + 'activity';
        }).catch((err) => {
            console.log(err);
            // self.router.navigate(["/activity"]);
            window.location.href = self.configService.getYxbUrl() + 'activity';
            
        })
        
    }
    sendSmsCode(){
        var self = this;
        //手机输入不过关
        
        if(self.phone_error){
            alert("手机号输入有误，请确认后重新输入");
            self.lockSmsCode(3)
        }
        else if(self.allowSms) {//true才允许
            self.loginService.getSmsCode(self.phone_input).then((res)=> {
                if(res.data.resultCode == 0){
                    //让登录按钮可点击
                    // alert("验证码已发送～");
                    self.lockSmsCode(60);
                    self.allowSubmit = true;
                }else{
                    alert("获取验证码失败，原因为"+res.data.msg);
                }
            }).catch((err) => {
                    alert('获取验证码超时，请重试'); 
                    // alert('err  '+err);   
                }
            );
        }
        
    }
    lockSmsCode(sec){
        var self = this;
        self.allowSms = false;
        self.smsCount = sec;
        var timeinterval = setInterval(function(){
            self.smsCount--;
            if(self.smsCount == 0){
                clearInterval(timeinterval);
                self.unlockSmsCode()
            }
        },1000);
    }
    unlockSmsCode(){
        var self = this;
        self.allowSms = true;
    }
    submitSmsCode(){
        var self = this;
        
        //如果不允许使用提交按钮 allow = false
        if(!self.allowSubmit){
            alert('手机号码或验证码输入有误，请重新输入');
        }
        else{
            self.phoneNum = self.phone_input;
            this.userNum = this.phoneNum.substring(7,11);
            self.loginService.getCheck(self.phone_input,self.sms_input).then((res)=>{
                if(res.data.resultCode == 0){
                    //登录通过
                    alert("登录成功！")
                    localStorage.setItem("phone",self.phoneNum);
                    localStorage.setItem("tail",self.phoneNum.substring(7,11));
                    self.loginWindow();
                    self.loginService.getUser(self.phoneNum).then(
                        (res)=>{
                            if(res.data.msg.name){
                                self.userName = res.data.msg.name;
                            }
                            else{
                                self.userName = "小镇居民"
                            }
                                localStorage.setItem("name",self.userName);
                                self.btnAnimate();
                        }
                    ).catch((err)=>{
                        alert('网络无连接，请刷新后重试。（3）')
                    })
                }else{
                    alert('登录失败，原因为 ：'+res.data.msg);
                }
            }).catch((res)=>{
                alert("登录超时，请重试");
            }
            );
        }
    }
    formPhone(event:any){
        var self = this;
        self.phone_error = true;   
		//判断手机号码格式是否正确
		var r = new RegExp(/^(((13\d|14[57]|15[^4,\D]|17[678]|18\d)\d{8})|(170[059]\d{7}))$/);
		var value = event.target.value;
		var result = r.test(value);
	    if(result == true){
			self.phone_error = false;
            self.phone_input = value;
        }else if(result == false){
            self.phone_error = true;
        }
    }
    formSms(event:any){
        var self = this;
        var value = event.target.value;
        self.sms_input = value;
    }
    judgeUrl(){
        var self = this;
        var id = window.location.href.split("?").reverse()[0].split('=')[1];
        console.log("id="+id);
        this.stampId = parseInt(id);
        localStorage.setItem('stampId',id);
        
    }
    
    checkAll(){
        var self = this;
        if(self.stampId == 11){

            self.loginService.get11(localStorage.getItem("phone")).then((res)=>{
                // if(res.data.code == 1){
                //     alert("你还没有足够的邮戳哦～")
                // }
                
                // self.router.navigate(["/activity"]);
                window.location.href = self.configService.getYxbUrl() + 'activity';
                
            }).catch(()=>{ 
                // self.router.navigate(["/activity"]);
                alert("网络连接失败，请刷新重试。")                
            });
        }
    }
    
}
